<?php

namespace app\api\controller;

use app\admin\model\shopro\ThirdOauth;
use app\common\controller\Api;
use app\common\library\RabbitMQ as RabbitMQLib;
use app\common\model\User;
use fast\Random;

/**
 * RabbitMQ API控制器
 * 提供RabbitMQ消息发送和接收的API接口
 */
class RabbitMq extends Api
{
    // 无需登录的接口
    protected $noNeedLogin = ['send', 'send_with_response'];
    // 无需鉴权的接口
    protected $noNeedRight = ['*'];

    /**
     * 发送RabbitMQ消息
     *
     * @ApiTitle    (发送消息)
     * @ApiSummary  (向RabbitMQ发送消息)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/rabbitmq/send)
     * @ApiParams   (name="message", type="string", required=true, description="消息内容")
     * @ApiParams   (name="data", type="object", description="附加数据")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="消息发送成功")
     */
    public function send()
    {
//        try {
            $message = $this->request->post('message');
            $data = $this->request->post('data/a', []);


//            $data = $this->request->post('data/a', []);
//            $unionid = $data['unionid'];
//            $score = $data['score'];
//
//            $thirdOauth =  ThirdOauth::field('id,user_id')->where('unionid', $unionid)->find();
//
//            if(!$thirdOauth){
//                $username = $unionid;
//                $password = 123456;
//                $email = $username . '@163.com';
//                $time = time();
//                $ip = request()->ip();
//
//                $salt =  Random::alnum();
//                $userData = [
//                    'username' => $username,
//                    'password' => $password,
//                    'email'    => $email,
//                    'group_id'    => 1,
//                    'level'    => 1,
//                    'score'    => 0,
//                    'avatar'   => '',
//                ];
//                $params = array_merge($userData, [
//                    'nickname'  => preg_match("/^1[3-9]{1}\d{9}$/", $username) ? substr_replace($username, '****', 3, 4) : $username,
//                    'salt'      => $salt,
//                    'jointime'  => $time,
//                    'joinip'    => $ip,
//                    'logintime' => $time,
//                    'loginip'   => $ip,
//                    'prevtime'  => $time,
//                    'status'    => 'normal'
//                ]);
//                $params['password'] =  md5(md5($password) . $salt);
//
//                $user = User::create($params);
//
//                if ($user) {
//                    $thirdOauth = ThirdOauth::create([
//                        'user_id' => $user->id,
//                        'openid' => '',
//                        'unionid' => $unionid,
//                        'provider' => 'wechat',
//                        'platform' => 'miniProgram',
//                        'nickname' => $unionid,
//                        'avatar' => '',
//                        'createtime' => $time,
//                        'updatetime' => $time
//                    ]);
//
//                }
//                $user_id = $user->id;
//            }else{
//                $user_id = $thirdOauth['user_id'];
//            }
//
//            // 变更会员积分
//            User::score($score, $user_id, '直播积分变更');
//            die;


            if (!$message) {
                $this->error('消息内容不能为空');
            }

            // 创建RabbitMQ实例
            $rabbitMQ = new RabbitMQLib();

            // 准备消息数据
            $messageData = [
                'message' => $message,
                'data' => $data,
                'timestamp' => time(),
                'sender' => 'api',
            ];
            // 发送消息
            $rabbitMQ->send($messageData);



//        } catch (\Exception $e) {
//            $this->error('消息发送失败: ' . $e->getMessage());
//        }
        $this->success('消息发送成功');
    }

    /**
     * 发送RabbitMQ消息并等待响应
     *
     * @ApiTitle    (发送消息并等待响应)
     * @ApiSummary  (向RabbitMQ发送消息并等待消费者响应)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/rabbitmq/send_with_response)
     * @ApiParams   (name="message", type="string", required=true, description="消息内容")
     * @ApiParams   (name="data", type="object", description="附加数据")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="消息发送成功")
     */
    public function send_with_response()
    {
        try {
            $message = $this->request->post('message');
            $data = $this->request->post('data/a', []);

            if (!$message) {
                $this->error('消息内容不能为空');
            }

            // 创建RabbitMQ实例
            $rabbitMQ = new RabbitMQLib();

            // 准备消息数据
            $correlationId = uniqid();
            $replyTo = 'response_queue_' . uniqid();

            $messageData = [
                'message' => $message,
                'data' => $data,
                'timestamp' => time(),
                'sender' => 'api',
                'reply_to' => $replyTo,
                'correlation_id' => $correlationId,
            ];

            // 发送消息
            $rabbitMQ->send($messageData);

            $this->success('消息发送成功，已等待消费者响应');

        } catch (\Exception $e) {
            $this->error('消息发送失败: ' . $e->getMessage());
        }
    }
}